import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入路由配置
import routes from './routes_config'

// 导入vuex
import store from '@/store'

// 处理新版本路由警告
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

Vue.use(VueRouter)

const router = new VueRouter({
  routes
})

// 路由访问拦截
/**
 * to: 去哪
 * from: 从哪里来
 * next：控制是否能访问页面
 */
router.beforeEach((to, from, next) => {
  /**
   * 说明：访问我的页面做拦截
   */
  const { user } = store.state
  if (to.path.startsWith('/user') && !user.token) {
    // 登录配置
    const loginConfig = { path: '/login', query: { backUrl: to.path } }
    next(loginConfig)
  } else {
    next()
  }
})

export default router
